<template>
  <div style="width: 100%; height: 100%">
    <el-header class="el-header">
      <div class="header-back-container">
        <div class="el-page-header">
          <div class="el-page-header__left" @click="onBack">
            <i class="el-icon-back"></i>
            <div class="el-page-header__title">返回</div>
          </div>
          <div class="el-page-header__content">
            <div class="title-box">
              <div class="title">
                {{ editData && editData.id ? "编辑消防设施" : "新增消防设施" }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-header>
    <el-main style="height: calc(100% - 60px - 60px); overflow-y: auto">
      <div class="info-title">基础信息</div>
      <el-form
        :model="formBasic"
        :rules="rulesBasic"
        inline
        ref="refFormBasic"
        label-width="110px"
        label-position="top"
        style="margin: 0px 8px; padding: 0px 20px"
      >
        <el-form-item label="消防设施名称" prop="facilityName">
          <el-input
            v-model.trim="formBasic.facilityName"
            placeholder="请输入"
            maxlength="30"
            style="width: 340px"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="组织机构"
          prop="orgId"
          v-if="user.roleName == 'TENANT_ADMIN' || user.roleName == 'ORG_ADMIN'"
        >
          <!-- v-if="!editData.id" -->
          <TreeSearchAdd
            style="width: 340px"
            @changeOrgId="changeOrgId"
            :clearable="false"
            ref="refTreeSearchAdd"
            v-if="!editData.id"
          >
            <!-- :disabled="editData && editData.id ? true : false" -->
          </TreeSearchAdd>
          <el-input
            v-else
            disabled
            style="width: 340px"
            v-model="orgName"
            placeholder="组织机构"
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="联网单位" prop="unitId">
          <el-select
            size="small"
            style="width: 340px"
            v-model="formBasic.unitId"
            placeholder="请选择联网单位"
            filterable
            @change="changeunitId"
            :disabled="editData && editData.id ? true : false"
          >
            <el-option
              v-for="item in orgList"
              :label="item.orgName"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="建筑物" prop="buildingId">
          <el-select
            size="small"
            style="width: 340px"
            @change="changeBuildings"
            v-model="formBasic.buildingId"
            v-loadMore="loadBulidings"
            placeholder="请选择建筑物"
            filterable
            remote
            :remote-method="remoteBuildings"
            :disabled="editData && editData.id ? true : false"
          >
            <el-option
              v-for="item in buildings"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="楼层" prop="floorId">
          <el-select
            size="small"
            style="width: 340px"
            clearable
            @change="changeFloors"
            v-loadMore="loadFloors"
            v-model="formBasic.floorId"
            placeholder="请选择楼层"
            filterable
            remote
            :remote-method="remoteFloors"
            :disabled="editData && editData.id ? true : false"
          >
            <!-- @clear="clearFloors" -->
            <el-option
              v-for="item in floors"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading3"
              :style="loading3 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="安装点" prop="spaceId">
          <el-select
            size="small"
            style="width: 340px"
            clearable
            @change="changeSpaces"
            v-loadMore="loadSpaces"
            v-model="formBasic.spaceId"
            placeholder="请选择安装点"
            filterable
            remote
            :remote-method="remoteSpaces"
            @clear="clearSpaces"
            :disabled="editData && editData.id ? true : false"
          >
            <el-option
              v-for="item in spaces"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading4"
              :style="loading4 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="规格型号" prop="specificationNum">
          <el-input
            v-model="formBasic.specificationNum"
            placeholder="请输入"
            style="width: 340px"
            size="small"
            clearable
          ></el-input>
        </el-form-item> -->
        <el-form-item label="消防系统" prop="fireOsType">
          <el-select
            v-model="formBasic.fireOsType"
            placeholder="请选择"
            size="small"
            @change="changeSystem"
            :disabled="editData && editData.id ? true : false"
            style="width: 340px"
          >
            <el-option
              v-for="item in systemList"
              :key="item.id"
              :label="item.name"
              :value="item.osType"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施类型" prop="facilityType">
          <el-select
            v-model="formBasic.facilityType"
            placeholder="请选择"
            size="small"
            :disabled="editData && editData.id ? true : false"
            style="width: 340px"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.facilityCategoryKey"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施位置" prop="mark">
          <el-input
            v-model="formBasic.mark"
            placeholder="请输入"
            maxlength="30"
            style="width: 340px"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="设施编号" prop="facilityNumber">
          <el-input
            v-model="formBasic.facilityNumber"
            placeholder="请输入"
            maxlength="20"
            :disabled="editData && editData.id ? true : false"
            style="width: 340px"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="设施状态"
          prop="facilityStateName"
          v-if="editData && editData.id ? true : false"
        >
          <el-input
            v-model="formBasic.facilityStateName"
            placeholder="请输入"
            maxlength="30"
            :disabled="editData && editData.id ? true : false"
            style="width: 340px"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="info-title">关联设备</div>
      <div class="associated-devices">
        <div class="header" style="margin-bottom: 10px">
          <div class="header_left">
            <el-button
              class="el_button"
              size="small"
              icon="el-icon-plus"
              @click="addClick"
            >
              新增
            </el-button>
            <el-button
              class="el_button"
              size="small"
              icon="el-icon-delete"
              type="info"
              style="margin-left: 15px"
              @click="onDelClickBatch"
            >
              删除
            </el-button>
          </div>
          <div class="header_right"></div>
        </div>
        <div class="content">
          <el-table
            :data="dataList"
            class="table"
            max-height="400"
            :header-cell-style="headerStyle"
            ref="refTable"
            row-key="deviceCode"
            @selection-change="batchSelect"
          >
            <el-table-column
              align="center"
              type="selection"
              :reserve-selection="true"
              width="60"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="deviceCode"
              label="设备编码"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              align="center"
              prop="type"
              label="设备类型"
              min-width="100"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.type == 1 ? "设备" : "探测器" }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="spaceName"
              label="安装点"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column align="center" label="操作" width="150">
              <template slot-scope="scope">
                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="bottom"
                >
                  <i
                    @click="editClick(scope.row)"
                    class="iconfont tianxie tableBtnIcon"
                  ></i>
                </el-tooltip> -->
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="bottom"
                >
                  <i
                    @click="onDel(scope.row)"
                    class="iconfont shanchu tableBtnIcon"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="info-title">维护及报废生命周期管理</div>
      <el-form
        :model="formMaintenance"
        :rules="rulesMaintenance"
        inline
        ref="refFormMaintenance"
        label-width="110px"
        label-position="top"
        style="margin: 0px 8px; padding: 0px 20px"
      >
        <el-form-item label="生产日期" prop="produceTime">
          <el-date-picker
            v-model="formMaintenance.produceTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 340px"
            size="small"
            :disabled="editData && editData.id ? true : false"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期至" prop="expirationTime">
          <el-date-picker
            v-model="formMaintenance.expirationTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 340px"
            size="small"
            :picker-options="getPickerOptions2()"
            :disabled="
              (editData && editData.id) || !formMaintenance.produceTime
                ? true
                : false
            "
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="投运日期" prop="runingTime">
          <el-date-picker
            v-model="formMaintenance.runingTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 340px"
            size="small"
            :picker-options="getPickerOptions2()"
            :disabled="
              (editData && editData.id) || !formMaintenance.expirationTime
                ? true
                : false
            "
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始维护日期" prop="startServiceTime">
          <el-date-picker
            v-model="formMaintenance.startServiceTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 340px"
            size="small"
            :picker-options="getPickerOptions3()"
            :disabled="
              (editData && editData.id) || !formMaintenance.runingTime
                ? true
                : false
            "
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维护周期" prop="serviceYear">
          <el-select
            v-model="formMaintenance.serviceYear"
            placeholder="请选择"
            size="small"
            :disabled="editData && editData.id ? true : false"
            style="width: 340px"
          >
            <el-option
              v-for="item in cycleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维护人" prop="serviceUsers">
          <el-input
            v-model="formMaintenance.serviceUsers"
            placeholder="请选择"
            style="width: 340px"
            size="small"
            @focus="onFocus"
            readonly="readonly"
          ></el-input>
        </el-form-item>
      </el-form>
      <div style="height: 14px"></div>
    </el-main>
    <el-footer class="dialog-footer">
      <el-button size="small" @click="closeDialog">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="onSubmit"
        v-preventReClick="1000"
        >确 定</el-button
      >
    </el-footer>
    <choseDevice
      ref="refChoseDevice"
      :orgId="formBasic.orgId"
      :unitId="formBasic.unitId"
      :buildingId="formBasic.buildingId"
      :floorId="formBasic.floorId"
      :spaceId="formBasic.spaceId"
      :choseData1="choseData1"
      :choseData2="choseData2"
      @getDevices="getDevices"
    />
    <choseUser
      ref="refChoseUser"
      :orgId="formBasic.orgId"
      :unitId="formBasic.unitId"
      :userData="userData"
      @getUsers="getUsers"
    />
  </div>
</template>

<script>
import tableStyleMixin from "@mixin/table-style";
import { mapState } from "vuex";
import {
  reqProductList,
  reqProductModelPage,
  reqOrgList,
  reqSpaceManager,
  reqFireOsList,
  reqFireFacilityAdd,
  reqFireFacilityEdit,
  reqCategoryFireFacilityList,
  reqFireFacilityById,
} from "@/api/api";
import { reqRuleEdit } from "@api/rule";
import { reqByProductKey } from "@/api/rule";
// import rules from "../../isolateManage/mixins/rules";
import choseDevice from "./choseDevice.vue";
import choseUser from "./choseUser.vue";
import TreeSearchAdd from "@components/TreeSearchAdd.vue";
import loadMore from "@mixin/loadMore";

export default {
  name: "",
  props: ["showIndex", "editData"],
  components: { TreeSearchAdd, choseDevice, choseUser },
  watch: {
    showIndex(val) {
      if (JSON.stringify(this.editData) == "{}") {
        this.isEditInfo = false;
        if (
          this.user.roleName == "TENANT_ADMIN" ||
          this.user.roleName == "ORG_ADMIN"
        ) {
          if (this.$refs.refTreeSearchAdd) {
            this.$refs.refTreeSearchAdd.getDataList();
          }
        } else if (this.user.roleName == "UNIT_ADMIN") {
          this.getOrgList();
        }
        // 消防系统
        this.getFireOsList();
      } else {
        // 编辑
        this.isEditInfo = true;
        let data = JSON.parse(JSON.stringify(this.editData));
        this.getFireFacilityById(data.id);
      }
    },
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      isEditInfo: false,
      orgName: "",
      formBasic: {
        facilityType: "",
        mark: "",
        facilityName: "",
        facilityNumber: "",
        // specificationNum: "",
        fireOsType: "",
        facilityStateName: "",
        unitId: "",
        spaceId: "",
        buildingId: "",
        floorId: "",
        orgId: "",
      },
      rulesBasic: {
        facilityName: [
          { required: true, message: "请输入消防设施名称", trigger: "blur" },
        ],
        fireOsType: [
          { required: true, message: "请选择消防系统", trigger: "change" },
        ],
        facilityType: [
          { required: true, message: "请选择设施类型", trigger: "change" },
        ],
        orgId: [{ required: true, message: "请选择机构", trigger: "change" }],
        unitId: [{ required: true, message: "请选择单位", trigger: "change" }],
        buildingId: [
          { required: true, message: "请选择建筑物", trigger: "change" },
        ],
        floorId: [{ required: true, message: "请选择楼层", trigger: "change" }],
        spaceId: [
          { required: true, message: "请选择安装点", trigger: "change" },
        ],
        facilityNumber: [
          { required: true, message: "请输入设施编号", trigger: "blur" },
        ],
      },
      systemList: [],
      categoryList: [],
      formMaintenance: {
        produceTime: "",
        expirationTime: "",
        runingTime: "",
        startServiceTime: "",
        serviceYear: "",
        serviceUser: [],
        serviceUsers: "",
      },
      rulesMaintenance: {
        produceTime: {
          required: true,
          message: "请选择生产日期",
          trigger: "change",
        },
        expirationTime: {
          required: true,
          message: "请选择有效期",
          trigger: "change",
        },
        runingTime: {
          required: true,
          message: "请选择投运日期",
          trigger: "change",
        },
        startServiceTime: {
          required: true,
          message: "请选择开始维护日期",
          trigger: "change",
        },
        serviceYear: {
          required: true,
          message: "请选择维护周期",
          trigger: "change",
        },
        serviceUsers: [
          {
            required: true,
            message: "请选择维护人",
            trigger: ["blur", "change"],
          },
        ],
      },
      userData: [],
      cycleList: [
        {
          label: "1年",
          value: 1,
        },
        {
          label: "2年",
          value: 2,
        },
        {
          label: "3年",
          value: 3,
        },
        {
          label: "4年",
          value: 4,
        },
        {
          label: "5年",
          value: 5,
        },
        {
          label: "6年",
          value: 6,
        },
        {
          label: "7年",
          value: 7,
        },
        {
          label: "8年",
          value: 8,
        },
        {
          label: "9年",
          value: 9,
        },
        {
          label: "10年",
          value: 10,
        },
      ],
      dataList: [],
      batchDataList: [],
      orgList: [],
      buildings: [],
      buildingsName: "",
      sysInstanceIndex2: 0,
      sysInstanceTotalPages2: 10,
      loading2: false,
      floors: [],
      floorId: "",
      floorsName: "",
      floorsName2: "",
      sysInstanceIndex3: 1,
      sysInstanceTotalPages3: 10,
      loading3: false,

      spaces: [],
      loading4: false,
      spacesName: "",
      spacesName2: "",
      sysInstanceIndex4: 1,
      sysInstanceTotalPages4: 10,
      choseData1: [],
      choseData2: [],
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  methods: {
    getPickerOptions2() {
      const _this = this;
      return {
        disabledDate(time) {
          // 如果 formMaintenance.produceTime 不存在，则不限制日期
          if (!_this.formMaintenance.produceTime) {
            return false;
          }
          // 将 formMaintenance.produceTime 转换为 Date 对象
          const produceTime = new Date(_this.formMaintenance.produceTime);
          // 禁用早于 produceTime 的日期
          return time.getTime() < produceTime.getTime();
        },
      };
    },
    getPickerOptions3() {
      const _this = this;
      return {
        disabledDate(time) {
          // 如果 formMaintenance.produceTime 不存在，则不限制日期
          if (!_this.formMaintenance.produceTime) {
            return false;
          }
          // 将 formMaintenance.produceTime 转换为 Date 对象
          const produceTime = new Date(_this.formMaintenance.produceTime);
          const expirationTime = new Date(_this.formMaintenance.expirationTime);
          // 禁用早于 produceTime 的日期
          return (
            time.getTime() < produceTime.getTime() ||
            time.getTime() > expirationTime.getTime()
          );
        },
      };
    },
    // 根据id查询消防设施信息
    async getFireFacilityById(id) {
      let res = await reqFireFacilityById(id);
      if (res.code !== 20000) return this.$modal.notifyError(res.message);
      let { info } = res.data;
      this.orgName = info.orgName;
      this.formBasic.facilityType = info.facilityType;
      this.formBasic.mark = info.mark;
      this.formBasic.facilityName = info.facilityName;
      this.formBasic.facilityNumber = info.facilityNumber;
      this.formBasic.fireOsType = info.fireOsType;
      this.formBasic.facilityStateName =
        info.status === 0 ? "报废" : info.status === 1 ? "正常" : "将报废";
      this.formBasic.unitId = info.unitId;
      this.formBasic.spaceId = info.spaceId;
      this.formBasic.buildingId = info.buildingId;
      this.formBasic.floorId = info.floorId;
      this.formBasic.orgId = info.orgId;

      this.formMaintenance.produceTime = info.produceTime
        ? info.produceTime
        : "";
      this.formMaintenance.expirationTime = info.expirationTime
        ? info.expirationTime
        : "";
      this.formMaintenance.runingTime = info.runingTime ? info.runingTime : "";
      this.formMaintenance.startServiceTime = info.startServiceTime
        ? info.startServiceTime
        : "";
      this.formMaintenance.serviceYear = info.serviceYear;
      this.userData = info.serviceUser;
      this.formMaintenance.serviceUser = info.serviceUser;
      this.formMaintenance.serviceUsers = info.serviceUser
        .map((item) => item.username)
        .join(",");
      if (info.deviceList.length) {
        info.deviceList.forEach((item) => {
          if (item.type == 1) {
            item.imei = item.deviceCode;
            this.choseData1.push(item);
          } else {
            this.choseData2.push(item);
          }
        });
        this.dataList = info.deviceList;
      } else {
        this.choseData1 = [];
        this.choseData2 = [];
        this.dataList = [];
      }

      this.getOrgList();
      this.getBuildList();
      this.getFloors();
      this.getSpaces();
      this.getFireOsList();
      this.getCategoryFireFacilityList();
      // this.$nextTick(() => {
      //   this.$refs.refTreeSearchAdd.getDataList(this.formBasic.orgId); //机构列表
      //   this.$refs.refTreeSearchAdd.getValue(this.formBasic.orgId); //机构赋值
      // });
    },

    // ——————————————————————————————————————单位
    async getOrgList() {
      let { tenantId, userId, roleName } = this.user;
      const res = await reqOrgList({
        tenantId,
        userId,
        roleName,
        orgName: this.orgName || "",
        parentId: this.formBasic.orgId || "",
        type: "4",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.orgList = res.data.rows;
    },
    changeunitId() {
      // this.formBasic.userIds = [];
      // this.orgUserList = [];
      // this.getOrgUserList();
      this.formBasic.buildingId =
        this.formBasic.floorId =
        this.formBasic.spaceId =
          "";
      this.buildings = this.floors = this.spaces = [];
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.getBuildList();
      // this.deviceList1 = [];
      // this.deviceList2 = [];
      // this.$refs.refTable1.clearData();
      // this.$refs.refTable2.clearData();
    },
    // 组织机构
    changeOrgId(instanceId) {
      if (this.isEditInfo) return;
      this.formBasic.orgId = instanceId.id;
      this.handleClear();
    },
    // 清空
    handleClear() {
      this.orgName = "";
      this.orgList = [];
      this.getOrgList();

      this.formBasic.unitId =
        this.formBasic.buildingId =
        this.formBasic.floorId =
        this.formBasic.spaceId =
          "";
      this.buildings = this.floors = this.spaces = [];
      this.formBasic.buildingId = this.formBasic.floorId = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
    },

    // ——————————————————————————————————————建筑物
    // 选择建筑物
    changeBuildings(e) {
      this.formBasic.buildingId = e;
      this.clearFloors();
    },
    // 建筑物列表
    async getBuildList() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 1,
        orgId: this.formBasic.unitId,
        isStatistics: 0,
        name: this.buildingsName,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.buildings = [...this.buildings, ...res.data.rows];
    },

    // 建筑物操作
    async loadBulidings() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getBuildList();
      this.loading2 = false;
    },

    // 远程搜索
    async remoteBuildings(query) {
      this.buildingsName = query; //保留输入的值
      this.buildingsName2 = query; //保留输入的值
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = [];
      this.getBuildList();
    },
    // ——————————————————————————————————————楼层
    // 选择楼层
    changeFloors(e) {
      this.formBasic.floorId = e;
      this.clearSpaces();
    },
    // 清空楼层
    clearFloors() {
      this.formBasic.floorId = this.formBasic.spaceId = "";
      this.floorsName = "";
      this.floorsName2 = "";
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.floors = this.spaces = [];
      this.getFloors();
    },
    // 远程搜索
    async remoteFloors(query) {
      this.floorsName = query; //保留输入的值
      this.floorsName2 = query; //保留输入的值
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.floors = [];
      this.getFloors();
    },
    // 楼层操作
    async loadFloors() {
      if (this.sysInstanceIndex3 >= Math.ceil(this.sysInstanceTotalPages3 / 10))
        return;
      this.sysInstanceIndex3++;
      this.loading3 = true;
      // 获取列表数据的方法
      await this.getFloors();
      this.loading3 = false;
    },
    async getFloors() {
      let res = await reqSpaceManager(this.sysInstanceIndex3, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 2,
        orgId: this.formBasic.unitId,
        isStatistics: 0,
        name: this.floorsName,
        parentId: this.formBasic.buildingId || "",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages3 = res.data.total;
      this.floors = [...this.floors, ...res.data.rows];
    },
    // ——————————————————————————————————————安装点
    // 选择安装点
    changeSpaces(e) {
      this.formBasic.spaceId = e;
    },
    // 清空安装点
    clearSpaces() {
      this.spacesName = "";
      this.spacesName2 = "";
      this.sysInstanceIndex4 = 1;
      this.sysInstanceTotalPages4 = 10;
      this.spaceId = "";
      this.spaces = [];
      this.getSpaces();
    },
    // 远程搜索
    async remoteSpaces(query) {
      this.spacesName = query; //保留输入的值
      this.spacesName2 = query; //保留输入的值
      this.sysInstanceIndex4 = 1;
      this.sysInstanceTotalPages4 = 10;
      this.spaces = [];
      this.getSpaces();
    },
    // 安装点操作
    async loadSpaces() {
      if (this.sysInstanceIndex4 >= Math.ceil(this.sysInstanceTotalPages4 / 10))
        return;
      this.sysInstanceIndex4++;
      this.loading4 = true;
      // 获取列表数据的方法
      await this.getSpaces();
      this.loading4 = false;
    },
    async getSpaces() {
      console.log(this.spacesName, "this.spacesName");
      let res = await reqSpaceManager(this.sysInstanceIndex4, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 3,
        orgId: this.formBasic.unitId,
        isStatistics: 0,
        name: this.spacesName,
        parentId: this.formBasic.floorId || "",
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages4 = res.data.total;
      this.spaces = [...this.spaces, ...res.data.rows];
    },

    // ——————————————————————————————————————消防系统
    changeSystem(e) {
      this.formBasic.facilityType = "";
      this.getCategoryFireFacilityList();
    },
    // 消防系统列表
    async getFireOsList() {
      let res = await reqFireOsList({
        name: "",
        osTypes: [],
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.systemList = res.data.list;
    },

    // ——————————————————————————————————————消防系统分类
    // 消防系统分类列表
    async getCategoryFireFacilityList() {
      let res = await reqCategoryFireFacilityList({
        name: "",
        osTypes: [this.formBasic.fireOsType],
        facilityTypes: [],
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.categoryList = res.data.list;
    },

    // ——————————————————————————————————————关联设备
    // 获取子组件传过来的设备数据
    getDevices(data1, data2) {
      this.choseData1 = data1;
      this.choseData2 = data2;
      [...this.choseData1, ...this.choseData2].forEach((item) => {
        if (item && item.imei) {
          item.type = 1;
          item.deviceCode = item.imei;
        } else {
          item.type = 2;
        }
      });
      this.dataList = [...this.choseData1, ...this.choseData2];
    },

    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      this.batchDataList = arr;
    },
    // 新增
    addClick() {
      if (this.formBasic.orgId == "")
        return this.$modal.notifyWarning("请先选择组织机构");
      if (this.formBasic.unitId == "")
        return this.$modal.notifyWarning("请先选择联网单位");
      if (this.formBasic.buildingId == "")
        return this.$modal.notifyWarning("请先选择建筑物");
      if (this.formBasic.floorId == "")
        return this.$modal.notifyWarning("请先选择楼层");
      if (this.formBasic.spaceId == "")
        return this.$modal.notifyWarning("请先选择安装点");
      if (this.dataList.length) {
        this.choseData = JSON.parse(JSON.stringify(this.dataList));
      } else {
        this.choseData = [];
      }
      this.$refs.refChoseDevice.dialogVisible = true;
    },
    // 批量删除
    onDelClickBatch() {
      this.batchDataList.forEach((item, index) => {
        if (item.type == 1) {
          this.choseData1 = this.choseData1.filter(
            (item1) => item1.imei != item.imei
          );
        } else {
          this.choseData2 = this.choseData2.filter(
            (item2) => item2.deviceCode != item.deviceCode
          );
        }
        if (index == this.batchDataList.length - 1) {
          this.dataList = [...this.choseData1, ...this.choseData2];
        }
      });
    },
    // 删除
    onDel(row) {
      console.log(row, "row");
      if (row.type == 1) {
        this.choseData1 = this.choseData1.filter(
          (item) => item.imei != row.imei
        );
      } else {
        this.choseData2 = this.choseData2.filter(
          (item) => item.deviceCode != row.deviceCode
        );
      }
      this.dataList = [...this.choseData1, ...this.choseData2];
    },

    // 维护人
    onFocus() {
      if (this.formBasic.orgId == "")
        return this.$modal.notifyWarning("请先选择组织机构");
      if (this.formBasic.unitId == "")
        return this.$modal.notifyWarning("请先选择联网单位");
      this.$refs.refChoseUser.dialogVisible = true;
    },
    getUsers(data) {
      this.userData = data;
      this.formMaintenance.serviceUser = data.map((item) => {
        return {
          userId: item.userId,
          username: item.username,
          nickname: item.nickname,
        };
      });
      this.formMaintenance.serviceUsers = data
        .map((item) => item.username)
        .join(",");
    },
    onBack() {
      this.closeDialog();
    },
    async onSubmit() {
      this.$refs.refFormBasic.validate(async (valid) => {
        if (valid) {
          this.$refs.refFormMaintenance.validate(async (valid2) => {
            if (valid2) {
              let res;
              this.formBasic.tenantId = this.user.tenantId;
              this.formBasic.deviceList = this.dataList.map((item) => {
                return {
                  type: item.type,
                  deviceCode: item.type == 1 ? item.imei : item.deviceCode,
                  id: item.id,
                  productType:
                    item && item.productType
                      ? item.productType
                      : item.deviceType,
                  spaceName: item.spaceName,
                };
              });
              let addForm_copy = { ...this.formBasic, ...this.formMaintenance };
              if (JSON.stringify(this.editData) != "{}") {
                res = await reqFireFacilityEdit(this.editData.id, addForm_copy);
                if (res.code !== 20000)
                  return this.$modal.notifyWarning(res.message);
                this.$modal.notifySuccess("编辑成功");
              } else {
                res = await reqFireFacilityAdd(addForm_copy);
                if (res.code !== 20000)
                  return this.$modal.notifyWarning(res.message);
                this.$modal.notifySuccess("新增成功");
              }
              this.$parent.getDataList();
              this.closeDialog();
            }
          });
        }
      });
    },
    closeDialog() {
      this.formBasic.deviceList = [];
      this.formMaintenance.serviceUser = [];
      this.formMaintenance.serviceUsers = "";
      this.userData = [];
      this.orgList = [];
      this.buildings = [];
      this.floors = [];
      this.spaces = [];
      this.choseData1 = [];
      this.choseData2 = [];
      this.dataList = [];
      this.orgName = "";
      this.$refs.refTable.clearSelection();
      this.$refs.refFormBasic.resetFields();
      this.$refs.refFormMaintenance.resetFields();
      this.$parent.isShowRuleOperate = false;
    },
  },
};
</script>

<style scoped lang="less">
@import url("./fpdOperate.less");
</style>
